package com.hfut.wxy.common;

import com.alibaba.fastjson.JSON;
import com.hfut.wxy.entity.mongo.WxyChat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{orderId}/{userId}")
public class WebSocket {
//
//    private static final String PREFIX = "webSocket:";
//
//    private static final String IS_USER_ONLINE = ":isOnline";

    private static MongoTemplate mongoTemplate;

//    private static final String COLLECTION_NAME = "wxy";

    @Autowired
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        WebSocket.mongoTemplate = mongoTemplate;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 以用户id为key，Session为对象保存起来
     */
    private static final Map<String, Session> clients = new ConcurrentHashMap<>();


    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(@PathParam("orderId") Integer orderId,@PathParam("userId") Integer userId, Session session)  {
        logger.info("现在来连接的订单id：" + orderId + "用户id：" + userId);
        String key = orderId+""+userId;
        //把自己的信息加入到map当中去
        if (!clients.containsKey(key)){
            clients.put(key, session);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("服务端发生了错误" + error.getMessage());
        String errorUser = null;
        for (Map.Entry<String, Session> entry : clients.entrySet()) {
            if (entry.getValue().getId().equals(session.getId())){
                errorUser = entry.getKey();
                break;
            }
        }
        if (errorUser!=null){
            clients.remove(errorUser);
        }
        error.printStackTrace();
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("orderId") Integer orderId,@PathParam("userId") Integer userId) {
        logger.info(userId+"断开了连接,订单id:"+orderId);
        String key = orderId+""+userId;
        clients.remove(key);
    }
    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(@PathParam("orderId") Integer orderId,@PathParam("userId") Integer userId,String message, Session session) {
        try {
            WxyChat wxyChat = JSON.parseObject(message, WxyChat.class);
            wxyChat.setSender(userId);
            wxyChat.setOrderId(orderId);
            logger.info("来自客户端消息：" + message);
            String key = orderId+""+wxyChat.getReceiver();
            Session receiver = clients.get(key);
            if (receiver == null|| !receiver.isOpen()){
                // TODO: 2020/4/29 微信推送
            } else {
                receiver.getAsyncRemote().sendText(wxyChat.getMessage());
            }
            wxyChat.setSendTime(new Date());
            mongoTemplate.insert(wxyChat);
        } catch (Exception e) {
            logger.info("发生了错误了");
            e.printStackTrace();
        }
    }
}
